#ifndef XMPPMANAGER_H
#define XMPPMANAGER_H
#include "xmpp.h"
#include "contactitem.h"
#include <QThread>
#include <QEvent>
#include <QMutex>
#include <QWaitCondition>

extern int EVENT_LOGIN;
extern int EVENT_LOGOFF;
extern int EVENT_CONTACT_INFO;
extern int EVENT_CONTACT_INFOS;
extern int EVENT_MESSAGE_RECEIVED;
extern int EVENT_MESSAGE_SESSION;

class LogoffEvent : public QEvent
{
public:
    LogoffEvent(int error):QEvent((QEvent::Type)EVENT_LOGOFF), errorCode(error){}
    int errorCode;
};

class ContactEvent : public QEvent
{
public:
    ContactEvent(Type type):QEvent(type){}
    ContactItem contact;
};

class ContactsEvent : public QEvent
{
public:
    ContactsEvent(std::vector<ContactItem> const& val):QEvent((QEvent::Type)EVENT_CONTACT_INFOS)
    {
        contacts = val;
    }
    std::vector<ContactItem> contacts;
};

class MessageSessionEvent : public QEvent
{
public:
    MessageSessionEvent(gloox::MessageSession * val, QWaitCondition& wc)
        :QEvent((QEvent::Type)EVENT_MESSAGE_SESSION),
        condition(wc)
    {
        session = val;
    }
    virtual ~MessageSessionEvent()
    {
        condition.wakeAll();
    }

    gloox::MessageSession* session;
    QWaitCondition & condition;
};

class XmppManager : public QThread, public XmppEventHandler
{
//    Q_OBJECT
public:
    explicit XmppManager();//QObject *parent = 0
    void run();
    bool login(QString& id, QString& password);
    void logout();
    bool requestVcard(QString& jid);
    static XmppManager& instance(){
        static XmppManager mgr;
        return mgr;
    }
    gloox::MessageSession* createSession(std::string& jid);
    void closeSession(gloox::MessageSession* session);

    void addLoginEventHandler(QObject* pHandler)
    {
        m_LoginHandlers.push_back(pHandler);
    }

    void removeLoginEventHandler(QObject* pHandler)
    {
        m_LoginHandlers.remove(pHandler);
    }

    void addContactEventHandler(QObject* pHandler)
    {
        m_ContactHandlers.push_back(pHandler);
    }

    void removeContactEventHandler(QObject* pHandler)
    {
        m_ContactHandlers.remove(pHandler);
    }

    void addMessageSessionEventHandler(QObject* pHandler)
    {
        m_MessageSessionHandlers.push_back(pHandler);
    }

    void removeMessageSessionEventHandler(QObject* pHandler)
    {
        m_MessageSessionHandlers.remove(pHandler);
    }

protected:
    virtual void onConnect();
    virtual void onDisconnect(int const error);
    virtual void onContactItem(ContactItem& item);
    virtual void onContactItems(std::vector<ContactItem>& items);
    virtual void onMessageSession(gloox::MessageSession *session);


//signals:

//public slots:

private:
    QString m_strId;
    QString m_strPassword;
    std::list<QObject*> m_LoginHandlers;
    std::list<QObject*> m_ContactHandlers;
    std::list<QObject*> m_MessageSessionHandlers;
};

#endif // XMPPMANAGER_H
